package com.ayf.payment.game.api.service.impl;

import com.ayf.payment.game.api.cache.CacheKey;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.SiteStatisticsDTO;
import com.ayf.payment.game.api.dto.SiteStatisticsSummaryDTO;
import com.ayf.payment.game.api.dto.criteria.CleanCriteria;
import com.ayf.payment.game.api.dto.criteria.SiteStatisticsCriteria;
import com.ayf.payment.game.api.entity.SiteStatistics;
import com.ayf.payment.game.api.mapper.SiteStatisticsMapper;
import com.ayf.payment.game.api.service.SiteStatisticsService;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.MD5Util;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class SiteStatisticsServiceImpl implements SiteStatisticsService {

    @Resource
    private SiteStatisticsMapper siteStatisticsMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Override
    public void saveSiteStatistics(SiteStatisticsDTO siteStatisticsDTO) {
        Example example = new Example(SiteStatistics.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("generateTimeIndex", siteStatisticsDTO.getGenerateTimeIndex());
        criteria.andEqualTo("merchantId", siteStatisticsDTO.getMerchantId());
        criteria.andEqualTo("siteUrl", siteStatisticsDTO.getSiteUrl());
        SiteStatistics siteStatisticsReturn = siteStatisticsMapper.selectOneByExample(example);
        Date currentDate = siteStatisticsDTO.getCreateTime();

        // 放进缓存便于订单数量和订单金额的统计
        String tempKey = siteStatisticsDTO.getMerchantId() + "_" + siteStatisticsDTO.getPlayerIp()+"_"+siteStatisticsDTO.getGenerateTimeIndex();
        tempKey = MD5Util.strToMd5(tempKey);
        String key = CacheKey.KEY_SITE_STATISTICS_GENERATE_DATE_MERCHANT_ID_PLAYER_IP.concat(tempKey);

        if (siteStatisticsReturn == null) {
            siteStatisticsDTO.setVisitCount(Integer.valueOf(1));
            siteStatisticsDTO.setVisitPeopleCount(Integer.valueOf(1));
            SiteStatistics siteStatistics = BeanConvertUtils.convert(siteStatisticsDTO, SiteStatistics.class);
            siteStatistics.setLoginCount(Integer.valueOf(0));
            siteStatistics.setLoginPeopleCount(Integer.valueOf(0));
            siteStatistics.setIncomeAmt(BigDecimal.ZERO);
            siteStatistics.setRechargeAmt(BigDecimal.ZERO);
            siteStatistics.setOrderNum(Integer.valueOf(0));
            siteStatistics.setCreateTime(currentDate);
            siteStatistics.setLastUpdateTime(currentDate);
            siteStatisticsMapper.insert(siteStatistics);
        } else {
            SiteStatistics upSiteStatistics = new SiteStatistics();
            upSiteStatistics.setId(siteStatisticsReturn.getId());
            upSiteStatistics.setVisitCount(1);
            upSiteStatistics.setLastUpdateTime(currentDate);
            if (Objects.isNull(redisCacheUtil.getObjectFromCache(key))){
                upSiteStatistics.setVisitPeopleCount(1);
            }
            siteStatisticsMapper.updateSiteStatisticsVistLoginCount(upSiteStatistics);
        }
        redisCacheUtil.setObjectToCacheDelayMilliSeconds(key, siteStatisticsDTO.getSiteUrl(),DateUtils.getNextDayIntervalMilliSecond(currentDate));
    }

    @Override
    public void saveSiteStatisticsPlayers(SiteStatisticsDTO siteStatisticsDTO) {
        String tempKey = siteStatisticsDTO.getMerchantId() + "_" + siteStatisticsDTO.getPlayerIp()+"_"+siteStatisticsDTO.getGenerateTimeIndex();
        tempKey = MD5Util.strToMd5(tempKey);
        String key = CacheKey.KEY_SITE_STATISTICS_GENERATE_DATE_MERCHANT_ID_PLAYER_IP.concat(tempKey);
        String siteUrl = redisCacheUtil.getObjectFromCache(key);
        if (StringUtils.isNotBlank(siteUrl)) {
            tempKey = siteStatisticsDTO.getMerchantId() + "_" + siteStatisticsDTO.getPlayerIp()+"_"+siteStatisticsDTO.getGenerateTimeIndex()+"_"+siteUrl;
            tempKey = MD5Util.strToMd5(tempKey);
            String loginPeopleCountKey = CacheKey.KEY_SITE_STATISTICS_GENERATE_DATE_MERCHANT_ID_PLAYER_IP_SITE_URL.concat(tempKey);

            Example example = new Example(SiteStatistics.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("generateTimeIndex", siteStatisticsDTO.getGenerateTimeIndex());
            criteria.andEqualTo("merchantId", siteStatisticsDTO.getMerchantId());
            criteria.andEqualTo("siteUrl", siteUrl);
            SiteStatistics siteStatisticsReturn = siteStatisticsMapper.selectOneByExample(example);
            Date currentDate = siteStatisticsDTO.getCreateTime();
            if (siteStatisticsReturn != null) {
                SiteStatistics upSiteStatistics = new SiteStatistics();
                upSiteStatistics.setId(siteStatisticsReturn.getId());
                upSiteStatistics.setLoginCount(1);
                if (Objects.isNull(redisCacheUtil.getObjectFromCache(loginPeopleCountKey))){
                    upSiteStatistics.setLoginPeopleCount(1);
                }
                siteStatisticsMapper.updateSiteStatisticsVistLoginCount(upSiteStatistics);
            } else {
                siteStatisticsDTO.setVisitCount(Integer.valueOf(0));
                siteStatisticsDTO.setVisitPeopleCount(Integer.valueOf(0));
                SiteStatistics siteStatistics = BeanConvertUtils.convert(siteStatisticsDTO, SiteStatistics.class);
                siteStatistics.setLoginCount(Integer.valueOf(1));
                siteStatistics.setLoginPeopleCount(Integer.valueOf(1));
                siteStatistics.setIncomeAmt(BigDecimal.ZERO);
                siteStatistics.setRechargeAmt(BigDecimal.ZERO);
                siteStatistics.setOrderNum(Integer.valueOf(0));
                siteStatistics.setCreateTime(currentDate);
                siteStatistics.setSiteUrl(siteUrl);
                siteStatistics.setLastUpdateTime(currentDate);
                siteStatisticsMapper.insert(siteStatistics);
            }
            redisCacheUtil.setObjectToCacheDelayMilliSeconds(key, siteUrl, DateUtils.getNextDayIntervalMilliSecond(currentDate));
            redisCacheUtil.setObjectToCacheDelayMilliSeconds(loginPeopleCountKey,1, DateUtils.getNextDayIntervalMilliSecond(currentDate));
        }
    }

    @Override
    public void saveSiteStatisticsOrderNumAndChargeAmt(SiteStatisticsDTO siteStatisticsDTO) {
        String tempKey = siteStatisticsDTO.getMerchantId()+"_"+siteStatisticsDTO.getPlayerIp()+"_"+siteStatisticsDTO.getGenerateTimeIndex();
        LogPortal.info("充值统计 统计日期:{} 商户ID:{} 玩家IP:{} 玩家账号:{} ",siteStatisticsDTO.getGenerateTimeIndex(),siteStatisticsDTO.getMerchantId(),siteStatisticsDTO.getPlayerIp(),siteStatisticsDTO.getPlayerAccount());
        tempKey = MD5Util.strToMd5(tempKey);
        String key = CacheKey.KEY_SITE_STATISTICS_GENERATE_DATE_MERCHANT_ID_PLAYER_IP.concat(tempKey);
        String siteUrl = redisCacheUtil.getObjectFromCache(key);
        String traceId = SnowFlakeUtils.getTraceId();
        if (StringUtils.isNotEmpty(siteUrl)){
            Example example = new Example(SiteStatistics.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("generateTimeIndex",siteStatisticsDTO.getGenerateTimeIndex());
            criteria.andEqualTo("merchantId",siteStatisticsDTO.getMerchantId());
            criteria.andEqualTo("siteUrl",siteUrl);
            SiteStatistics siteStatisticsReturn = siteStatisticsMapper.selectOneByExample(example);
            if (siteStatisticsReturn != null){
                SiteStatistics siteStatistics = BeanConvertUtils.convert(siteStatisticsDTO,SiteStatistics.class);
                siteStatistics.setId(siteStatisticsReturn.getId());
                siteStatisticsMapper.updateSiteStatisticsOrderNumAndChargeAmt(siteStatistics);
            } else {
                Date currentDate = DateUtils.getNowDate();
                siteStatisticsDTO.setVisitCount(Integer.valueOf(1));
                SiteStatistics siteStatistics = BeanConvertUtils.convert(siteStatisticsDTO, SiteStatistics.class);
                siteStatistics.setLoginCount(Integer.valueOf(0));
                siteStatistics.setOrderNum(Integer.valueOf(1));
                siteStatistics.setCreateTime(currentDate);
                siteStatistics.setSiteUrl(siteUrl);
                siteStatistics.setLastUpdateTime(currentDate);
                siteStatisticsMapper.insert(siteStatistics);
            }
        } else {
            insertOtherUrlRechargeAmt(traceId,siteStatisticsDTO);
        }
    }

    /**
     * 插入未名URL的充值金额
     * @param traceId
     * @param siteStatisticsDTO
     */
    private void insertOtherUrlRechargeAmt(String traceId, SiteStatisticsDTO siteStatisticsDTO){
        Date currentDate = DateUtils.getNowDate();
        Example example = new Example(SiteStatistics.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("generateTimeIndex",siteStatisticsDTO.getGenerateTimeIndex());
        criteria.andEqualTo("merchantId",siteStatisticsDTO.getMerchantId());
        criteria.andEqualTo("siteUrl","直接登录");
        SiteStatistics siteStatisticsReturn = siteStatisticsMapper.selectOneByExample(example);
        if (siteStatisticsReturn==null){
            SiteStatistics siteStatistics = new SiteStatistics();
            siteStatistics.setLoginCount(Integer.valueOf(0));
            siteStatistics.setVisitCount(Integer.valueOf(0));
            siteStatistics.setIncomeAmt(siteStatisticsDTO.getIncomeAmt());
            siteStatistics.setRechargeAmt(siteStatisticsDTO.getRechargeAmt());
            siteStatistics.setOrderNum(Integer.valueOf(1));
            siteStatistics.setGenerateTimeIndex(siteStatisticsDTO.getGenerateTimeIndex());
            siteStatistics.setMerchantId(siteStatisticsDTO.getMerchantId());
            siteStatistics.setSiteUrl("直接登录");
            siteStatistics.setCreateTime(currentDate);
            siteStatistics.setLastUpdateTime(currentDate);
            siteStatisticsMapper.insert(siteStatistics);
        } else {
            SiteStatistics siteStatistics = BeanConvertUtils.convert(siteStatisticsDTO,SiteStatistics.class);
            siteStatistics.setId(siteStatisticsReturn.getId());
            siteStatisticsMapper.updateSiteStatisticsOrderNumAndChargeAmt(siteStatistics);
        }
    }

    @Override
    public SiteStatisticsSummaryDTO list(SiteStatisticsCriteria siteStatisticsCriteria) {
        PageHelper.startPage(siteStatisticsCriteria.getPageNum(), siteStatisticsCriteria.getPageSize());
        List<SiteStatistics> siteStatisticsList = siteStatisticsMapper.list(siteStatisticsCriteria);
        PageInfo pageInfo = new PageInfo(siteStatisticsList);
        List<SiteStatisticsDTO> list = BeanConvertUtils.convert(siteStatisticsList, SiteStatisticsDTO.class);
        SiteStatisticsSummaryDTO siteStatisticsSummaryDTO = siteStatisticsMapper.getSiteStatisticsSummary(siteStatisticsCriteria);
        if (siteStatisticsSummaryDTO == null) {
            siteStatisticsSummaryDTO = new SiteStatisticsSummaryDTO();
        }
        if (!CollectionUtils.isEmpty(list)) {
            siteStatisticsSummaryDTO.setNum(pageInfo.getTotal());
            siteStatisticsSummaryDTO.setList(list);
        }
        return siteStatisticsSummaryDTO;
    }

    @Override
    public int cleanSiteStatistics(CleanCriteria clean) {
        return siteStatisticsMapper.cleanSiteStatistics(clean);
    }
}


